
import { ActionReducer, INIT, UPDATE } from '@ngrx/store';
import { LocalStorageService } from '../local-storage/local-storage.service';
import { AppState } from '../cne.state';

/**
 * 从本地存储初始化状态的 Meta Reducer
 * 在应用启动时从 localStorage 恢复状态
 */
export function initStateFromLocalStorage(
  reducer: ActionReducer<AppState>
): ActionReducer<AppState> {
  return (state, action) => {
    const newState = reducer(state, action);
    
    // 在 INIT 和 UPDATE action 时从 localStorage 恢复状态
    if ([INIT.toString(), UPDATE.toString()].includes(action.type)) {
      return { 
        ...newState, 
        ...LocalStorageService.loadInitialState() 
      };
    }
    
    return newState;
  };
}
